import { createRef, RefObject } from 'react'
import type { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import { ITplRouteListItem, ITplRouteListReq, ITplRouteListRes } from './interface'

export type TRequest = Result<ITplRouteListRes, [ITplRouteListReq]>

export interface IStore {
  gridRef: RefObject<AgGridReact<ITplRouteListItem>>
  request?: TRequest
  reqData: ITplRouteListReq
  setReqData: (val: Partial<ITplRouteListReq> | ((prevVal: ITplRouteListReq) => ITplRouteListReq)) => void
  getData: (scrollToTop?: boolean) => void
}

export const defaultParams: ITplRouteListReq = {
  templateCn: undefined,
  routeNode: undefined,
  logisticsStatus: undefined,
  page: 1,
  size: DEFAULT_PAGE_SIZE,
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    reqData: { ...defaultParams },
    setReqData: val => {
      set(prev => {
        return {
          reqData: {
            ...prev.reqData,
            ...(typeof val === 'function' ? val(prev.reqData) : val),
          },
        }
      })
    },
    getData: scrollToTop => {
      const { gridRef, request, reqData } = get()
      request?.run(reqData)
      if (scrollToTop) gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
  }
})
